package com.franklin.ideaplugin.easytesting.spring.lifecycle;

import com.franklin.ideaplugin.easytesting.common.label.EasyTestingLabel;
import com.franklin.ideaplugin.easytesting.common.utils.EnvUtils;
import com.franklin.ideaplugin.easytesting.core.invoke.MethodInvokerRegistry;
import com.franklin.ideaplugin.easytesting.common.log.ILogger;
import com.franklin.ideaplugin.easytesting.common.log.LoggerFactory;
import com.franklin.ideaplugin.easytesting.core.registry.FileRegistry;
import com.franklin.ideaplugin.easytesting.core.rpc.NettyServer;
import com.franklin.ideaplugin.easytesting.core.thread.EasyTestingThreadPool;
import com.franklin.ideaplugin.easytesting.spring.config.EasyTestingProperties;
import com.franklin.ideaplugin.easytesting.spring.invoke.SpringMethodInvoker;
import com.franklin.ideaplugin.easytesting.spring.invoke.SpringScriptObjectPropertyFiller;
import com.franklin.ideaplugin.easytesting.spring.registry.SpringFileRegistry;
import com.franklin.ideaplugin.easytesting.spring.utils.SpringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

/**
 * @author Ye Junhui
 * @since 2023/5/21
 */
@RequiredArgsConstructor
public class EasyTestingLifeCycle implements InitializingBean, ApplicationListener<ContextClosedEvent> {

    private final static ILogger logger = LoggerFactory.getLogger(EasyTestingLifeCycle.class);

    private final SpringMethodInvoker springMethodInvoker;
    private final NettyServer nettyServer;
    private final EasyTestingProperties easyTestingProperties;
    private final SpringFileRegistry springFileRegistry;
    private final SpringScriptObjectPropertyFiller springScriptObjectPropertyFiller;


    @Override
    public void afterPropertiesSet() throws Exception {
        if (!nettyServer.isEnable()){
            return;
        }
//        if (!EnvUtils.isValidEnv()){
//            return;
//        }

        //打印标签
        EasyTestingLabel.print();

        //注册方法调用器
        MethodInvokerRegistry.addMethodInvoker(springMethodInvoker);

        //注册脚本对象填充器
        MethodInvokerRegistry.addScriptObjectPropertyFillerList(springScriptObjectPropertyFiller);

        //启动netty服务器
        nettyServer.start();

        //注册方法
        springFileRegistry.doRegistry();

        //打印标签
        EasyTestingLabel.print();

    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        logger.info("Easy-Testing-Server stopping");
        this.close();
    }

    private void close(){
        nettyServer.shutDown();
        EasyTestingThreadPool.shutDownAll();
        FileRegistry.shutDown(SpringUtil.getAppName());
    }
}
